//
//  HMEmoticonToolBar.swift
//  Black22
//
//  Created by Apple on 16/11/26.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

enum HMEmoticonToolBarType: Int {
    //  最近
    case recent = 1000
    //  默认
    case normal = 1001
    //  emoji
    case emoji = 1002
    //  浪小花
    case lxh = 1003
}

//  表情键盘，toolbar视图
class HMEmoticonToolBar: UIStackView {

    //  上次选中的按钮
    var lastSelectedButton: UIButton?
    
    //  闭包执行回调
    var callBack: ((HMEmoticonToolBarType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //  水平布局方式
        axis = .horizontal
        //  子控件填充方式
        distribution = .fillEqually
        
        addChildButton(title: "最近", imageName: "compose_emotion_table_left", type: .recent)
        addChildButton(title: "默认", imageName: "compose_emotion_table_mid", type: .normal)
        addChildButton(title: "Emoji", imageName: "compose_emotion_table_mid", type: .emoji)
        addChildButton(title: "浪小花", imageName: "compose_emotion_table_right", type: .lxh)
        
    }
    
    private func addChildButton(title: String, imageName: String, type: HMEmoticonToolBarType) {
        let button = UIButton()
        button.tag = type.rawValue
        button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
        //  去掉高亮效果
        button.adjustsImageWhenHighlighted = false
        button.setTitle(title, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .selected)
        button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), for: .normal)
        button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), for: .selected)
        addArrangedSubview(button)
        
        if type == .normal {
            lastSelectedButton?.isSelected = false
            button.isSelected = true
            lastSelectedButton = button
        }
    }
    
    @objc func btnAction(btn: UIButton) {
        
        if lastSelectedButton == btn {
            return
        }
        
        lastSelectedButton?.isSelected = false
        btn.isSelected = true
        lastSelectedButton = btn
        let type = HMEmoticonToolBarType(rawValue: btn.tag)!
        callBack?(type)
    }
    
    func selectedButton(section: Int) {
        let button = viewWithTag(1000 + section) as! UIButton
        if button == lastSelectedButton {
            return
        }
        
        lastSelectedButton?.isSelected = false
        
        button.isSelected = true
        
        lastSelectedButton = button
    }
    
    

}
